/* Default Integration Javascript for Create Material Model

	This resource is referenced by the MaterialModelMapping.xml file
	
	The following interface functions must be present:
		void calculateDefaults(SimMgrDbObject material, SimMgrDbObject mapping, List<String> nameAndId)
		String validateForSubmit(SimMgrDbObject material, SimMgrDbObject mapping, List<String> nameAndId)
		String get_library_datafile_name(String library_name, String solver)
		String post_library(String library_name, String solver, String s)
*/
    
var Long = java.lang.Long;
var String = java.lang.String;
    
function calculateDefaults(uil, material, mapping, solver, nameAndId, defaultId) {
	var id = null;
	if (nameAndId.length > 1)
		id = nameAndId.get(1);
		
	var name = null;
	if (nameAndId.length >= 1)
		name = nameAndId.get(0);
				
	// determine name
	if (name == null || name == "") {
		var mappingName = mapping.evaluate("name").getString();
		name = String.format("%s; %s", mappingName, solver);
	}
	
	var el = String.format("generates[name == '%s'].sort(createdAt, 'd')", name, material.getId());
	var existing = material.evaluate(el).getDbObjectList();
	if (existing != null && existing.size() > 0){
		id = existing.get(0).evaluate("ID").getString();
	} else if (id != null && id != "") {		
		if (conn.search("MatMaterialModel", String.format("[ID=='%s' AND solver=='%s']", id, solver)).size() > 0) {
			id = null; // Proposed id already in use
		}
	}
	
	if(defaultId != null && defaultId != "NULL"){
		id= defaultId;
	}else{
		
		// try to reuse ID across solvers
		if (id == null || id == "") {
			var IDs = {};

			var el2 = String.format("generates:MatMaterialModel[solver=='%s'].ID", solver);
			var ids = material.evaluate(el2).getList();
			for(var i=0;i<ids.size();i++) {
				IDs[ids.get(i).getValue().getString()] = 1;			
			}

			ids = material.evaluate(String.format("generates:MatMaterialModel[solver!='%s'].ID", solver)).getList();
			for(var i=0;i<ids.size();i++) {
				var idcheck = ids.get(i).getValue().getString();
				if (IDs[idcheck] == 1) { continue; }

				var check = conn.search("MatMaterialModel", String.format("[ID=='%s' AND solver=='%s']", idcheck, solver));
				if (check.size() > 0) {
					// Proposed id already in use
					continue;
				}

				id = idcheck;			
			}
		}
		
		// determine a unique ID
		if (id == null || id == "") {
			// only calculate if not done before
			id = 1000;
			var latest = conn.search("MatMaterialModel", "sort(createdAt, 'd')[0]");
			if (latest.size() > 0) {
				var id2 = latest.get(0).evaluate("ID").getString();
				try {
					id2 = Long.parseLong(id2);
					id = id2+1;
				} catch(e) { } // ok to ignore

				while(conn.search("MatMaterialModel", String.format("[ID=='%s']", id)).size() > 0) {
					id++;
				}
			}
		}
	}
	
	// prepare return array
	nameAndId.clear();
	nameAndId.add(name);
	nameAndId.add(""+id);	
} 
	

function validateForSubmit(uil, matrial, mapping, solver, nameAndId) {
	var name = nameAndId.get(0);
	var id = nameAndId.get(1);

	// return null when there no errors.  otherwise, return a descriptive error string
	
	// This is already being done by default..
	// var latest = conn.search("MatMaterialModel", String.format("[ID == '%s']", id));
	// if (latest.size() > 0) {
	//	return "Error:  CAE Model already exists with id "+id;
	//}
	
	// Busines logic may be appplied here
	if (id < 1) {
		return "Error:  ID must not be less than 1";
	}
	
	if (!isNumeric(id)) {
		return "Error: ID must be a positive number";
	}
	
	return null;
}

function isNumeric(value) {
	return !isNaN(value)
}

function get_library_datafile_name(library_name, solver) {
	if (solver == "Abaqus") {
		return "mat_abaqus_master.inp";
	} else if (solver == "Ansys") {
		return "mat_ansys_master.txt";
	} else if (solver == "LS-Dyna") {
		return "mat_lsdyna_master.dyn";
	} else if (solver == "Marc") {
		return "mat_marc_master.dat";
	} else if (solver == "Nastran") {
		return "mat_master.nas";
	}
	return "mat_master.txt";
}

function post_library(library_name, solver, s) {
	// uncomment the below to demo encryption of Abaqus library files
	//if (solver == "Abaqus") {
	//	return post_demo_encrypt(s);
	//}
	return s;
}
    
function post_demo_encrypt(s) {
	var ret = s.replaceAll("[a-z]", "x");
	ret = ret.replaceAll("[A-Z]", "X");
	ret = ret.replaceAll("[0-9]", "#");
	return ret;
}

function post_demo_blank(s) {
	return "";
}

//This function returns value of global variable "CONTEXT_MATERIAL"
function getContextMaterial() {
	return CONTEXT_MATERIAL;
}

